//
//  AMapView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/9.
//


import SwiftUI
import AMapLocationKit
import AMapSearchKit

struct AMapView: UIViewRepresentable {
    @Binding var coordinate: CLLocationCoordinate2D?
    @Binding var address: String?
    let mapView = MAMapView()
    let search = AMapSearchAPI()
    
    func makeUIView(context: Context) -> MAMapView {
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        mapView.delegate = context.coordinator
        search?.delegate = context.coordinator
        return mapView
    }
    
    func updateUIView(_ uiView: MAMapView, context: Context) {
        if let coord = coordinate {
            let annotation = MAPointAnnotation()
            annotation.coordinate = coord
            uiView.addAnnotation(annotation)
            uiView.setCenter(coord, animated: true)
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, MAMapViewDelegate, AMapSearchDelegate {
        var parent: AMapView
        
        init(_ parent: AMapView) {
            self.parent = parent
        }
        
        // 自定义标记图标
        func mapView(_ mapView: MAMapView, viewFor annotation: MAAnnotation) -> MAAnnotationView? {
            if annotation.isKind(of: MAUserLocation.self) { return nil }
            let reuseId = "customAnnotation"
            let view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) ??
                       MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            view?.image = UIImage(named: "location_pin") // 自定义图标
            return view
        }
        // 定位回调
        func mapView(_ mapView: MAMapView, didUpdate userLocation: MAUserLocation, updatingLocation: Bool) {
            guard updatingLocation else { return }
            parent.coordinate = userLocation.coordinate
            reverseGeocode(coordinate: userLocation.coordinate)
        }
        // 逆地理编码
        func reverseGeocode(coordinate: CLLocationCoordinate2D) {
            let request = AMapReGeocodeSearchRequest()
            request.location = AMapGeoPoint.location(withLatitude: CGFloat(coordinate.latitude),longitude: CGFloat(coordinate.longitude))
            parent.search?.aMapReGoecodeSearch(request)
        }
        
        // 编码结果回调
        func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest, response: AMapReGeocodeSearchResponse) {
            parent.address = response.regeocode.formattedAddress
        }
        
        func amapLocationManager(_ manager: AMapLocationManager,
                                doRequireLocationAuth locationManager: CLLocationManager) {
            locationManager.requestAlwaysAuthorization() // 后台定位需此权限
        }
        
    }
}
